package com.lv.service.dialog

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Build
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.FragmentActivity
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lv.common.im.OnPositionMoreCancle
import com.lv.common.imp.OnPositionMediaTMore
import com.lv.common.imp.OnPositionTListener
import com.lv.common.imp.OnPositionTMore
import com.lv.common.ktx.LoadSrc
import com.lv.common.utils.AnimationUtils
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.common.utils.TimeUtil
import com.lv.common.utils.picengine.CompressEngine
import com.lv.common.utils.picengine.GlideEngine
import com.lv.common.utils.showToast
import com.lv.common.widget.popupview.TimeBottomCustomPopupView
import com.lv.service.R
import com.lv.service.bean.CommonSelectedBean
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupPosition
import com.lxj.xpopup.impl.PartShadowPopupView

/**
 * 作者： ygx
 * 创建日期：2022/10/10 10:32 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：底部 添加拜访记录
 */
class VisitEditorTopHPopupView(
    private val mContext: Context,
    private val mTitle: String,
    private val mType: Int = 0,//0 添加拜访记录 1 服务记录
    private val topH: Int = 0,
    private val mLayout: Int = R.layout.visit_editor_toph_popup,
    private val mPositionTListener: OnPositionMediaTMore<String>? = null
) :
    PartShadowPopupView(mContext), View.OnClickListener {
    private var tvTitle: TextView? = null
    private var viewTop: View? = null
    private var viewShadow: TextView? = null
    private var ivClose: ImageView? = null
    private var ivCamera: ImageView? = null
    private var ivMedia: ImageView? = null
    private var ivDelete: ImageView? = null
    private var mEtCaption: EditText? = null
    private var mTvCount: TextView? = null
    private var mTvTime: TextView? = null
    private var mTvType: TextView? = null
    private var mLlTime: LinearLayout? = null
    private var mLlType: LinearLayout? = null
    private var mStartTime = ""
    private var mEndTime = ""
    private var mSelectedTime = ""
    private var mStauts = ""
    private val mTypes = mutableListOf<CommonSelectedBean>()
    private val mBeans = mutableListOf<LocalMedia?>()

    override fun getImplLayoutId(): Int {
        return mLayout
    }

    override fun onCreate() {
        super.onCreate()

        initView()
        initEvnet()
    }

    private fun initView() {

        tvTitle = findViewById<TextView>(R.id.tv_title)
        viewTop = findViewById<View>(R.id.view_top)
        viewShadow = findViewById<TextView>(R.id.tv_submit)
        ivClose = findViewById<ImageView>(R.id.iv_close)
        ivCamera = findViewById<ImageView>(R.id.iv_camera)
        ivMedia = findViewById<ImageView>(R.id.iv_media)
        ivDelete = findViewById<ImageView>(R.id.iv_delete)
        mEtCaption = findViewById<EditText>(R.id.et_caption)
        mTvCount = findViewById<TextView>(R.id.tv_count)
        mLlTime = findViewById<LinearLayout>(R.id.ll_time)
        mLlType = findViewById<LinearLayout>(R.id.ll_type)
        mTvTime = findViewById<TextView>(R.id.tv_time)
        mTvType = findViewById<TextView>(R.id.tv_type)

        ivClose?.setOnClickListener(this)
        viewTop?.setOnClickListener(this)
        ivCamera?.setOnClickListener(this)
        ivDelete?.setOnClickListener(this)
        viewShadow?.setOnClickListener(this)
        mLlTime?.setOnClickListener(this)
        mLlType?.setOnClickListener(this)
        val layoutParams = viewTop?.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.height = topH
        tvTitle?.text = mTitle

        mTypes.clear()
        when (mType) {
            0 -> {
                mTypes.add(CommonSelectedBean("潜在客户", tag = "0", selected = true))
                mTypes.add(CommonSelectedBean("了解客户", tag = "1"))
                mTypes.add(CommonSelectedBean("意向客户", tag = "2"))
            }

            else -> {
                mTypes.add(CommonSelectedBean("稳定维护", tag = "3", selected = true))
                mTypes.add(CommonSelectedBean("产生售后", tag = "4"))
            }
        }
        mStartTime = TimeUtil.getToday("yyyy-MM-dd")
        val year = TimeUtil.getYear() + 2
        mEndTime = "$year-12"
        val days = TimeUtil.getDaysByDate(mEndTime)
        mEndTime = "$year-12-${days}"
        mSelectedTime = mStartTime
        mTvTime?.text = mSelectedTime

        mStauts = mTypes[0].tag
        mTvType?.text = mTypes[0].name
    }


    private fun initEvnet() {
        mEtCaption?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence, start: Int, count: Int, after: Int
            ) {
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                mTvCount?.text = "${(s.length)}/50"
            }

            override fun afterTextChanged(s: Editable) {
            }
        })


    }

    private fun showTimePicker() {
        val popupView =
            TimeBottomCustomPopupView(mContext,
                mStartTime, mEndTime, mSelectedTime, -1,
                "日期选择", false, false,
                object : OnPositionMoreCancle<String> {
                    override fun onConfirmClick(vararg args: Int, data: String?) {
                        mSelectedTime = data ?: ""
                        mTvTime?.text = data
                    }

                    override fun onConcelClick(tag: Int) {
                    }
                }
            )
        XPopup.Builder(mContext)
            .isViewMode(true)
            .popupPosition(PopupPosition.Bottom)
            .asCustom(popupView)
            .show()
    }

    private fun checkPermission() {
        val hasCamera =
            PermissionXUtils.hasPermission(mContext as Activity, Manifest.permission.CAMERA)
        val permissions = mutableListOf<String>()
        if (!hasCamera) {
            permissions.add(Manifest.permission.CAMERA)
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val hasRead =
                PermissionXUtils.hasPermission(
                    mContext, Manifest.permission.READ_MEDIA_IMAGES
                )
            if (!hasRead) {
                permissions.add(Manifest.permission.READ_MEDIA_IMAGES)
            }
        } else {
            val hasRead =
                PermissionXUtils.hasPermission(
                    mContext, Manifest.permission.READ_EXTERNAL_STORAGE
                )
            if (!hasRead) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }
        if (permissions.size == 0) {
            showPicSelector()
        } else {
            PermissionXUtils.checkPermissBefore(
                mContext as FragmentActivity,
                permissions,
                "请授予相机、存储权限，以便使用相机拍摄或在手机相册中选择图片",
                callback = object : PermissionXUtilsCallback {
                    override fun permissionCallback(
                        allGranted: Boolean,
                        grantedList: List<String?>,
                        deniedList: List<String?>
                    ) {
                        if (allGranted) {
                            showPicSelector()

                        }
                    }
                })
        }

    }

    private fun showPicSelector() {
        PictureSelector.create(mContext)
            .openGallery(SelectMimeType.ofImage())//图库显示的类型
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(CompressEngine.createCompressEngine())
            .setMaxSelectNum(1)//最大图片数
            .setMaxVideoSelectNum(1)//最大视频数
            .setMinSelectNum(1)
            .setImageSpanCount(4)
            .isMaxSelectEnabledMask(true)//不可点击时，是否显示朦层
            .isPreviewImage(true) // 是否可预览图片
            .isDisplayCamera(true) // 是否显示拍照按钮
            .isOriginalSkipCompress(true) // 是否压缩
            .setSelectedData(mBeans)
            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
            .isWithSelectVideoImage(false)//是否可以同时选择视频和图片
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    if (!result.isNullOrEmpty()) {
                        mBeans.clear()
                        val localMedia = result[0]
                        mBeans.add(localMedia)
                        ivMedia?.LoadSrc(localMedia?.compressPath ?: localMedia?.realPath)
                        ivMedia?.visibility = View.VISIBLE
                        ivDelete?.visibility = View.VISIBLE
                        ivCamera?.visibility = View.GONE
                    }

                }

                override fun onCancel() {}
            })
    }

    private fun setDismissDialog() {
        dismiss()
    }


    override fun onDestroy() {
        super.onDestroy()
    }

    override fun beforeDismiss() {
        super.beforeDismiss()


    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_close, R.id.view_top -> dismiss()
            R.id.iv_camera -> {
                checkPermission()
            }

            R.id.iv_delete -> {
                ivMedia?.visibility = View.GONE
                ivDelete?.visibility = View.GONE
                ivCamera?.visibility = View.VISIBLE
                mBeans.clear()
            }

            R.id.ll_time -> {
                showTimePicker()
            }

            R.id.ll_type -> {
                showTypePicker()
            }

            R.id.tv_submit -> {
                if (mBeans.isEmpty()) {
                    AnimationUtils.setHintAnimation(ivCamera)
                    return showToast("请选择门头或其它信息")
                }
                val remark = mEtCaption?.text?.trim()?.toString()
                mPositionTListener?.onClick(0, mBeans, remark, mSelectedTime, mStauts)
                dismiss()
            }

        }
    }

    private fun showTypePicker() {
        val popupView = RecyclerSelectedTagWhitePopupView(mContext as Activity, mTypes, "客户状态",
            mPositionTListener = OnPositionTListener<CommonSelectedBean> { position, data ->
//                mReson = data.name ?: ""
                mStauts = data?.tag ?: ""
                mTvType?.text = data?.name
            })
        XPopup.Builder(mContext)
            .isViewMode(true)
            .popupPosition(PopupPosition.Bottom)
            .asCustom(popupView)
            .show()
    }

}